<?php

namespace Kcdns\Service\Pay\SDK\Driver;


use Kcdns\Service\Pay\SDK\Pay;

class Shengpay extends \Think\Pay\Pay {

    protected $gateway = 'https://mas.shengpay.com/web-acquire-channel/cashier.htm';
    protected $config = array(
        'key' => '',
        'partner' => ''
    );

    public function check() {
        if (!$this->config['key'] || !$this->config['partner']) {
            E("盛付通设置有误！");
        }
        return true;
    }

    public function buildRequestForm(\Think\Pay\PayVo $vo) {
        $param = array(
			'Name' => 'B2CPayment',
			'Version' => 'V4.1.1.1.1',
            'Charset' => 'UTF-8',
            'MsgSender' => $this->config['partner'],
			'OrderNo' => $vo->getOrderNo(),
			'OrderAmount' => $vo->getFee(),
			'OrderTime' => date('YmdHis'),
			// 'PayType' => 'PT001',
			'PayChannel' => 19,
			'InstCode' => $vo->getBank(),
			'PageUrl' => $this->config['return_url'],
			'NotifyUrl' => $this->config['notify_url'],
			'ProductName' => $vo->getTitle(),
			'BuyerIp' => get_client_ip(),
			'SignType' => 'MD5',
        );

		$param['SignMsg'] = $this->createSign($param);

        $sHtml = $this->_buildForm($param, $this->gateway);

        return $sHtml;
    }
	
    /**
     * 创建签名
     * @param type $params
     */
    protected function createSign($params) {
        return strtoupper(md5(join('',array_filter($params)) . $this->config['key']));
    }

    public function verifyNotify($notify) {

        //提取服务器端的签名
        if (!isset($notify['SignMsg']) || !isset($notify['SignType'])) {
            return false;
        }
        $sign = $notify['SignMsg'];
		
		$keys=array("Name","Version","Charset","TraceNo","MsgSender","SendTime","InstCode","OrderNo","OrderAmount","TransNo","TransAmount","TransStatus","TransType","TransTime","MerchantNo","ErrorCode","ErrorMsg","Ext1","SignType");
		$param=array();
		foreach($keys as $key){
			$param[]=isset($notify[$key]) ? $notify[$key] : '';
		}
		
        //验证签名
        $mysign = $this->createSign($param);
		file_put_contents('./Runtime/'.$notify['OrderNo'].'_qm.html',var_export($notify,true).'<br />--->SignMsg:'.$sign.'--->my-SignMsg:'.$mysign.'--->key:'.$this->config['key']);
        if ($sign != $mysign) {
            return false;
        } else {
            $info = array();
            //支付状态
            $info['status'] = $notify['TransStatus'] == '01' ? true : false;
            $info['money'] = $notify['OrderAmount'];
            $info['out_trade_no'] = $notify['OrderNo'];
            $this->info = $info;
            return true;
        }
    }
	
	public function notifySuccess() {
        echo "OK";
    }
}
